import { reactive, ref, watch } from 'vue'
import type { DialogState, FormDialogOptions, FormState } from '../types'

export function useFormDialog(options: FormDialogOptions) {
  // 表单状态
  const formState = reactive<FormState>({
    data: {},
    initialData: {},
    isDirty: false,
    errors: {},
    loading: false,
    submitting: false,
  })

  // 对话框状态
  const dialogState = reactive<DialogState>({
    visible: false,
    title: options.title || '',
    width: options.width || '50%',
    fullscreen: options.fullscreen || false,
    top: options.top || '15vh',
    modal: options.modal ?? true,
    appendToBody: options.appendToBody || false,
    lockScroll: options.lockScroll ?? true,
    closeOnClickModal: options.closeOnClickModal ?? true,
    closeOnPressEscape: options.closeOnPressEscape ?? true,
    showClose: options.showClose ?? true,
    destroyOnClose: options.destroyOnClose || false,
    center: options.center || false,
    draggable: options.draggable || false,
  })

  // 表单引用
  const formRef = ref()

  // 方法
  const methods = {
    // 设置表单数据
    setFormData: (data: Record<string, any>) => {
      formState.data = { ...data }
      formState.initialData = { ...data }
      formState.isDirty = false
    },

    // 设置加载状态
    setLoading: (loading: boolean) => {
      formState.loading = loading
    },

    // 设置提交状态
    setSubmitting: (submitting: boolean) => {
      formState.submitting = submitting
    },

    // 设置错误信息
    setErrors: (errors: Record<string, string>) => {
      formState.errors = errors
    },

    // 验证表单
    validate: async () => {
      if (!formRef.value) return true
      return new Promise((resolve) => {
        formRef.value.validate((valid: boolean, fields: any) => {
          if (!valid) {
            formState.errors = fields
          }
          resolve(valid)
        })
      })
    },

    // 重置表单
    resetFields: () => {
      if (formRef.value) {
        formRef.value.resetFields()
        formState.isDirty = false
      }
    },

    // 打开对话框
    open: (formData?: Record<string, any>) => {
      if (formData) {
        methods.setFormData(formData)
      }
      dialogState.visible = true
    },

    // 关闭对话框
    close: () => {
      dialogState.visible = false
      if (options.resetOnClose) {
        methods.resetFields()
      }
    },
  }

  // 监听表单数据变化
  watch(
    () => formState.data,
    () => {
      formState.isDirty = true
    },
    { deep: true }
  )

  return {
    formState,
    dialogState,
    formRef,
    ...methods,
  }
}
